package com.jet.auth.service;

import com.jet.core.exception.CustomException;
import com.jet.core.utils.SecurityUtil;
import com.jet.merchant.domain.dto.OriginalPasswordResetDto;
import com.jet.auth.domain.dto.SmsCaptchaResetDto;
import com.jet.merchant.domain.entity.ClerkAccount;
import com.jet.merchant.service.IClerkAccountService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class RestPasswordService {

    @Resource
    private SmsCaptchaService smsCaptchaService;

    private final IClerkAccountService clerkAccountService;

    public RestPasswordService(IClerkAccountService clerkAccountService) {
        this.clerkAccountService = clerkAccountService;
    }

    /**
     * 重置用户密码
     *
     * @param dto 包含重置密码所需信息的DTO对象
     * @throws CustomException 如果两次输入的密码不一致或手机号信息错误，则抛出此异常
     */
    public void reset(SmsCaptchaResetDto dto) {
        if (!dto.getPassword().equals(dto.getConfirmPassword())) {
            throw new CustomException("两次密码不一致");
        }
        smsCaptchaService.validSmsCaptcha(dto.getPhone(), dto.getSmsCaptcha());
        ClerkAccount account = clerkAccountService.findByPhone(dto.getPhone());
        if (account == null) {
            throw new CustomException("修改失败：手机号信息错误");
        }
        String password = SecurityUtil.encryptPassword(dto.getPassword());
        clerkAccountService.editPassword(account.getId(), null, password);
    }

    /**
     * 重置用户密码
     *
     * @param dto 包含重置密码所需信息的DTO对象
     * @throws CustomException 如果两次输入的密码不一致、手机号信息错误或原密码错误，则抛出此异常
     */
    public void reset(OriginalPasswordResetDto dto) {
        if (!dto.getPassword().equals(dto.getConfirmPassword())) {
            throw new CustomException("两次密码不一致");
        }
        ClerkAccount account = clerkAccountService.findByPhone(dto.getPhone());
        if (account == null) {
            throw new CustomException("修改失败：不存在不存在");
        }
        if (!SecurityUtil.matchesPassword(dto.getOriginalPassword(), account.getPassword())) {
            throw new CustomException("修改失败：原密码错误");
        }
        String password = SecurityUtil.encryptPassword(dto.getPassword());
        clerkAccountService.editPassword(account.getId(), account.getPassword(), password);
    }
}
